using AutoMapper;
using Coldairarrow.Business;
using Coldairarrow.Business.Cache;
using Coldairarrow.Entity;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.SubApp
{
  public class UserSyncBusiness : BaseBusiness<Base_User>, IUserSyncBusiness, ITransientDependency
  {
    readonly IMapper _mapper;
    public UserSyncBusiness(
        IDbAccessor db,
        IBase_UserCache userCache,
        IMapper mapper
        )
        : base(db)
    {
      _userCache = userCache;
      _mapper = mapper;
    }
    IBase_UserCache _userCache { get; }
    protected override string _textField => "RealName";

    #region 外部接口
    [DataRepeatValidate(
           new string[] { "UserName" },
           new string[] { "用户名" })]
    [Transactional]
    public async Task AddDataAsync(UserSyncInputDTO input)
    {
      await InsertAsync(_mapper.Map<Base_User>(input));
      await SetUserRoleAsync(input.Id, input.RoleIdList);
      await WriteLog(UserLogType.系统用户管理, "添加用户：" + input.RealName);
    }


    [DataRepeatValidate(
           new string[] { "UserName" },
           new string[] { "用户名" })]
    [Transactional]
    public async Task UpdateDataAsync(UserSyncInputDTO input)
    {
      if (input.Id == GlobalData.ADMINID)
        throw new BusException("禁止更改超级管理员！");

      await UpdateAsync(_mapper.Map<Base_User>(input));
      await SetUserRoleAsync(input.Id, input.RoleIdList);
      await _userCache.UpdateCacheAsync(input.Id);
      await WriteLog(UserLogType.系统用户管理, "修改用户：" + input.RealName);
    }

    [Transactional]
    public async Task DeleteDataAsync(List<string> ids)
    {
      if (ids.Contains(GlobalData.ADMINID))
        throw new BusException("超级管理员是内置账号,禁止删除！");
      List<Base_User> users = new List<Base_User>();
      ids.ForEach(id => {
        var user = Service.GetEntity<Base_User>(id);
          if (user != null)
          {
              users.Add(user);
          }
      });

      await DeleteAsync(ids);

      await _userCache.UpdateCacheAsync(ids);
      var names = string.Join(",", users.Select(x => x.RealName).ToList());
      await WriteLog(UserLogType.系统用户管理, "删除用户：" + names);
    }

    public bool CheckExists(string id)
    {
        List<string> ids = new List<string>();
        ids.Add(id);
        var user = Service.GetEntity<Base_User>(id);
        if (user == null)
        {
        return false;
        }
        else
        {
          return true;
        }
    }
    

    /// <summary>
    /// 取得角色列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<RoleDTo>> GetRoleListAsync()
    {
      var q = Service.GetIQueryable<Base_Role>().Select(x => new RoleDTo { Id = x.Id, RoleName = x.RoleName });
      return await q.ToListAsync();
    }
    #endregion

    #region 私有成员
    private async Task WriteLog(UserLogType userLogType,string msg)
    {
      var log = new Base_UserLog
      {
        Id = IdHelper.GetId(),
        CreateTime = DateTime.Now,
        CreatorId = string.Empty,
        CreatorRealName = "远程数据同步",
        LogContent = msg,
        LogType = userLogType.ToString()
      };
      await Service.InsertAsync(log);
    }

    private async Task SetUserRoleAsync(string userId, List<string> roleIds)
    {
      roleIds = roleIds ?? new List<string>();
      var userRoleList = roleIds.Select(x => new Base_UserRole
      {
        Id = IdHelper.GetId(),
        CreateTime = DateTime.Now,
        UserId = userId,
        RoleId = x
      }).ToList();
      await Service.DeleteAsync<Base_UserRole>(x => x.UserId == userId);
      await Service.InsertAsync(userRoleList);
    }
    #endregion
  }
}